package com.tianyalei.wolf.sample.activity.wxcircle;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.tianyalei.wolf.mddesignlib.utils.AbAppUtil;
import com.tianyalei.wolf.mddesignlib.utils.ToastUtil;
import com.tianyalei.wolf.mddesignlib.view.autorecyclerview.callback.LoadMoreListener;
import com.tianyalei.wolf.sample.R;
import com.tianyalei.wolf.sample.activity.base.BaseToolBarActivity;
import com.tianyalei.wolf.sample.activity.wxcircle.adater.CircleAdapter;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.CircleItem;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.CommentConfig;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.CommentItem;
import com.tianyalei.wolf.sample.activity.wxcircle.bean.FavortItem;
import com.tianyalei.wolf.sample.activity.wxcircle.data.DatasUtil;
import com.tianyalei.wolf.sample.activity.wxcircle.listener.SwpipeListViewOnScrollListener;
import com.tianyalei.wolf.sample.activity.wxcircle.mvp.presenter.CirclePresenter;
import com.tianyalei.wolf.sample.activity.wxcircle.mvp.view.ICircleViewUpdateListener;
import com.tianyalei.wolf.sample.activity.wxcircle.widget.CommentListView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 放微信朋友圈图片展示界面
 */
public class WXCircleActivity extends BaseToolBarActivity implements ICircleViewUpdateListener {
    @Bind(R.id.mRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    /**
     * 列表
     */
    @Bind(R.id.circleLv)
    ListView mListView;
    /**
     * 输入框
     */
    @Bind(R.id.circleEt)
    EditText mCommentEdit;
    /**
     * 评论区域
     */
    @Bind(R.id.editTextBodyLl)
    LinearLayout editTextBodyLl;

    @Bind(R.id.detail_view)
    View mImageDetailView;

    private CirclePresenter mPresenter;

    private CircleAdapter mAdapter;

    private CommentConfig mCommentConfig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        //MVP模式
        mPresenter = new CirclePresenter(this);

        initView();

        loadData();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_wxcircle;
    }

    @Override
    public void onBackPressed() {
        //如果正在展示大图，先关闭大图，再关闭activity
        if (mImageDetailView.getVisibility() == View.VISIBLE) {
            mAdapter.closeViewDetail();
            return;
        }
        super.onBackPressed();
    }

    @OnClick(R.id.sendIv)
    public void onClick() {
        if (mPresenter != null) {
            //发布评论
            String content = mCommentEdit.getText().toString().trim();
            if (TextUtils.isEmpty(content)) {
                ToastUtil.showToast(this, "评论内容不能为空...");
                return;
            }
            mPresenter.addComment(content, mCommentConfig);
        }
        updateEditTextBodyVisible(View.GONE, null);
    }

    private void loadData() {
        List<CircleItem> datas = DatasUtil.createCircleDatas();
        mAdapter.setDatas(datas);
    }

    private void initView() {
        final SwpipeListViewOnScrollListener listener = new SwpipeListViewOnScrollListener(mSwipeRefreshLayout);
        mListView.setOnScrollListener(listener);
        listener.setLoadMoreListener(new LoadMoreListener() {
            @Override
            public void loadMore() {
                mAdapter.addDatas(DatasUtil.createCircleDatas());
                listener.loadFinish(null);
            }
        });
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (editTextBodyLl.getVisibility() == View.VISIBLE) {
                    updateEditTextBodyVisible(View.GONE, null);
                    return true;
                }
                return false;
            }
        });
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                mAdapter.loadFirst();
            }
        });
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        mAdapter = new CircleAdapter(this, DatasUtil.createCircleDatas());
        mAdapter.setCirclePresenter(mPresenter);
        mListView.setAdapter(mAdapter);

        setViewTreeObserver();
    }

    private int mScreenHeight;
    private int mEditTextBodyHeight;
    private int mCurrentKeyboardH;
    private int mSelectCircleItemH;
    private int mSelectCommentItemOffset;

    private void setViewTreeObserver() {

        final ViewTreeObserver swipeRefreshLayoutVTO = mSwipeRefreshLayout.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                mSwipeRefreshLayout.getWindowVisibleDisplayFrame(r);
                int statusBarH = getStatusBarHeight();//状态栏高度
                int screenH = mSwipeRefreshLayout.getRootView().getHeight();
                if (r.top != statusBarH) {
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);

                if (keyboardH == mCurrentKeyboardH) {//有变化时才处理，否则会陷入死循环
                    return;
                }

                mCurrentKeyboardH = keyboardH;
                mScreenHeight = screenH;//应用屏幕的高度
                mEditTextBodyHeight = mCommentEdit.getHeight();

                //偏移listview
                if (mListView != null && mCommentConfig != null) {
                    int index = mCommentConfig.circlePosition == 0 ? mCommentConfig.circlePosition : (mCommentConfig.circlePosition + mListView.getHeaderViewsCount());
                    mListView.setSelectionFromTop(index, getListviewOffset(mCommentConfig));
                }
            }
        });
    }

    /**
     * 测量偏移量
     *
     * @param commentConfig
     * @return
     */
    private int getListviewOffset(CommentConfig commentConfig) {
        if (commentConfig == null)
            return 0;
        //这里如果你的listview上面还有其它占高度的控件，则需要减去该控件高度，listview的headview除外。
        int listviewOffset = mScreenHeight - mSelectCircleItemH - mCurrentKeyboardH - mEditTextBodyHeight;
        if (commentConfig.commentType == CommentConfig.Type.REPLY) {
            //回复评论的情况
            listviewOffset = listviewOffset + mSelectCommentItemOffset;
        }
        return listviewOffset;
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void update2DeleteCircle(String circleId) {
        List<CircleItem> circleItems = mAdapter.getDatas();
        for (int i = 0; i < circleItems.size(); i++) {
            if (circleId.equals(circleItems.get(i).getId())) {
                circleItems.remove(i);
                mAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    @Override
    public void update2AddFavorite(int circlePosition, FavortItem addItem) {
        if (addItem != null) {
            mAdapter.getDatas().get(circlePosition).getFavorters().add(addItem);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void update2DeleteFavort(int circlePosition, String favortId) {
        List<FavortItem> items = mAdapter.getDatas().get(circlePosition).getFavorters();
        for (int i = 0; i < items.size(); i++) {
            if (favortId.equals(items.get(i).getId())) {
                items.remove(i);
                mAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    @Override
    public void update2AddComment(int circlePosition, CommentItem addItem) {
        if (addItem != null) {
            mAdapter.getDatas().get(circlePosition).getComments().add(addItem);
            mAdapter.notifyDataSetChanged();
        }
        //清空评论文本
        mCommentEdit.setText("");
    }

    @Override
    public void update2DeleteComment(int circlePosition, String commentId) {
        List<CommentItem> items = mAdapter.getDatas().get(circlePosition).getComments();
        for (int i = 0; i < items.size(); i++) {
            if (commentId.equals(items.get(i).getId())) {
                items.remove(i);
                mAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    @Override
    public void updateEditTextBodyVisible(int visibility, CommentConfig commentConfig) {
        mCommentConfig = commentConfig;
        editTextBodyLl.setVisibility(visibility);

        measureCircleItemHighAndCommentItemOffset(commentConfig);

        if (View.VISIBLE == visibility) {
            mCommentEdit.requestFocus();
            //弹出键盘
            AbAppUtil.showSoftInput(this);

        } else if (View.GONE == visibility) {
            //隐藏键盘
            AbAppUtil.closeSoftInput(this);
        }
    }

    private void measureCircleItemHighAndCommentItemOffset(CommentConfig commentConfig) {
        if (commentConfig == null)
            return;

        int headViewCount = mListView.getHeaderViewsCount();
        int firstPosition = mListView.getFirstVisiblePosition();
        //只能返回当前可见区域（列表可滚动）的子项
        View selectCircleItem = mListView.getChildAt(headViewCount + commentConfig.circlePosition - firstPosition);
        if (selectCircleItem != null) {
            mSelectCircleItemH = selectCircleItem.getHeight();
            if (headViewCount > 0 && firstPosition < headViewCount && commentConfig.circlePosition == 0) {
                //如果有headView，而且head是可见的，并且处理偏移的位置是第一条动态，则将显示的headView的高度合并到第一条动态上
                for (int i = firstPosition; i < headViewCount; i++) {
                    mSelectCircleItemH += mListView.getChildAt(i).getHeight();
                }
            }
        }

        if (commentConfig.commentType == CommentConfig.Type.REPLY) {
            //回复评论的情况
            CommentListView commentLv = (CommentListView) selectCircleItem.findViewById(R.id.commentList);
            if (commentLv != null) {
                //找到要回复的评论view,计算出该view距离所属动态底部的距离
                View selectCommentItem = commentLv.getChildAt(commentConfig.commentPosition);
                if (selectCommentItem != null) {
                    //选择的commentItem距选择的CircleItem底部的距离
                    mSelectCommentItemOffset = 0;
                    View parentView = selectCommentItem;
                    do {
                        int subItemBottom = parentView.getBottom();
                        parentView = (View) parentView.getParent();
                        if (parentView != null) {
                            mSelectCommentItemOffset += (parentView.getHeight() - subItemBottom);
                        }
                    } while (parentView != null && parentView != selectCircleItem);
                }
            }
        }
    }


}
